/**
 * Created with IntelliJ IDEA.
 * Description:求无重复字符的最长子串
 * User: bjc
 * Date: 2025-11-10
 * Time: 14:25
 */
public class Test02_lengthOfLongestSubstring {
    //方法1：暴力求解+哈希表（判断字符是否重复出现）
    public static int lengthOfLongestSubstring1(String s) {
        int ret = 0;
        int len = s.length();
        //1.遍历字符串
        for (int i = 0; i < len; i++) {
            int[] hash = new int[128];
            for (int j = i; j < len; j++) {
                char c = s.charAt(j);
                hash[c]++;
                if (hash[c] > 1)
                    break;
                //2.更新结果
                ret = Math.max(ret, j - i + 1);
            }
        }
        //3.返回结果
        return ret;
    }
    //方法2：滑动窗口+哈希表
    public static int lengthOfLongestSubstring2(String s) {
        int ret = 0;//最终返回结果
        int left = 0, right = 0;
        int len = s.length();
        int[] hash = new int[128];
        while (right < len) {
            char c = s.charAt(right);
            hash[c]++;//进窗口，让字符进入哈希表
            //判断是否重复
            while (hash[c] > 1){
                //出窗口,左侧出去
                char d = s.charAt(left);
                hash[d]--;
                left++;
            }
            ret = Math.max(ret, right - left + 1);//更新结果
            right++;//进窗口
        }
        return ret;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring1("abcabcbb"));
        System.out.println(lengthOfLongestSubstring2("abcabcbb"));

    }
}
